{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2fbeb3b6",
   "metadata": {},
   "source": [
    "一般有三种命名空间：\n",
    "内置名称（built-in names）， Python 语言内置的名称，比如函数名 abs、char 和异常名称 BaseException、Exception 等等。\n",
    "全局名称（global names），模块中定义的名称，记录了模块的变量，包括函数、类、其它导入的模块、模块级的变量和常量。\n",
    "局部名称（local names），函数中定义的名称，记录了函数的变量，包括函数的参数和局部定义的变量。（类中定义的也是）\n",
    "\n",
    "有四种作用域：\n",
    "L（Local）：最内层，包含局部变量，比如一个函数/方法内部。\n",
    "E（Enclosing）：包含了非局部(non-local)也非全局(non-global)的变量。比如两个嵌套函数，一个函数（或类） A 里面又包含了一个函数 B ，那么对于 B 中的名称来说 A 中的作用域就为 nonlocal。\n",
    "G（Global）：当前脚本的最外层，比如当前模块的全局变量。\n",
    "B（Built-in）： 包含了内建的变量/关键字等，最后被搜索。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3ac8ebbf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['ArithmeticError',\n",
       " 'AssertionError',\n",
       " 'AttributeError',\n",
       " 'BaseException',\n",
       " 'BaseExceptionGroup',\n",
       " 'BlockingIOError',\n",
       " 'BrokenPipeError',\n",
       " 'BufferError',\n",
       " 'BytesWarning',\n",
       " 'ChildProcessError',\n",
       " 'ConnectionAbortedError',\n",
       " 'ConnectionError',\n",
       " 'ConnectionRefusedError',\n",
       " 'ConnectionResetError',\n",
       " 'DeprecationWarning',\n",
       " 'EOFError',\n",
       " 'Ellipsis',\n",
       " 'EncodingWarning',\n",
       " 'EnvironmentError',\n",
       " 'Exception',\n",
       " 'ExceptionGroup',\n",
       " 'False',\n",
       " 'FileExistsError',\n",
       " 'FileNotFoundError',\n",
       " 'FloatingPointError',\n",
       " 'FutureWarning',\n",
       " 'GeneratorExit',\n",
       " 'IOError',\n",
       " 'ImportError',\n",
       " 'ImportWarning',\n",
       " 'IndentationError',\n",
       " 'IndexError',\n",
       " 'InterruptedError',\n",
       " 'IsADirectoryError',\n",
       " 'KeyError',\n",
       " 'KeyboardInterrupt',\n",
       " 'LookupError',\n",
       " 'MemoryError',\n",
       " 'ModuleNotFoundError',\n",
       " 'NameError',\n",
       " 'None',\n",
       " 'NotADirectoryError',\n",
       " 'NotImplemented',\n",
       " 'NotImplementedError',\n",
       " 'OSError',\n",
       " 'OverflowError',\n",
       " 'PendingDeprecationWarning',\n",
       " 'PermissionError',\n",
       " 'ProcessLookupError',\n",
       " 'RecursionError',\n",
       " 'ReferenceError',\n",
       " 'ResourceWarning',\n",
       " 'RuntimeError',\n",
       " 'RuntimeWarning',\n",
       " 'StopAsyncIteration',\n",
       " 'StopIteration',\n",
       " 'SyntaxError',\n",
       " 'SyntaxWarning',\n",
       " 'SystemError',\n",
       " 'SystemExit',\n",
       " 'TabError',\n",
       " 'TimeoutError',\n",
       " 'True',\n",
       " 'TypeError',\n",
       " 'UnboundLocalError',\n",
       " 'UnicodeDecodeError',\n",
       " 'UnicodeEncodeError',\n",
       " 'UnicodeError',\n",
       " 'UnicodeTranslateError',\n",
       " 'UnicodeWarning',\n",
       " 'UserWarning',\n",
       " 'ValueError',\n",
       " 'Warning',\n",
       " 'ZeroDivisionError',\n",
       " '__IPYTHON__',\n",
       " '__build_class__',\n",
       " '__debug__',\n",
       " '__doc__',\n",
       " '__import__',\n",
       " '__loader__',\n",
       " '__name__',\n",
       " '__package__',\n",
       " '__spec__',\n",
       " 'abs',\n",
       " 'aiter',\n",
       " 'all',\n",
       " 'anext',\n",
       " 'any',\n",
       " 'ascii',\n",
       " 'bin',\n",
       " 'bool',\n",
       " 'breakpoint',\n",
       " 'bytearray',\n",
       " 'bytes',\n",
       " 'callable',\n",
       " 'chr',\n",
       " 'classmethod',\n",
       " 'compile',\n",
       " 'complex',\n",
       " 'copyright',\n",
       " 'credits',\n",
       " 'delattr',\n",
       " 'dict',\n",
       " 'dir',\n",
       " 'display',\n",
       " 'divmod',\n",
       " 'enumerate',\n",
       " 'eval',\n",
       " 'exec',\n",
       " 'execfile',\n",
       " 'filter',\n",
       " 'float',\n",
       " 'format',\n",
       " 'frozenset',\n",
       " 'get_ipython',\n",
       " 'getattr',\n",
       " 'globals',\n",
       " 'hasattr',\n",
       " 'hash',\n",
       " 'help',\n",
       " 'hex',\n",
       " 'id',\n",
       " 'input',\n",
       " 'int',\n",
       " 'isinstance',\n",
       " 'issubclass',\n",
       " 'iter',\n",
       " 'len',\n",
       " 'license',\n",
       " 'list',\n",
       " 'locals',\n",
       " 'map',\n",
       " 'max',\n",
       " 'memoryview',\n",
       " 'min',\n",
       " 'next',\n",
       " 'object',\n",
       " 'oct',\n",
       " 'open',\n",
       " 'ord',\n",
       " 'pow',\n",
       " 'print',\n",
       " 'property',\n",
       " 'range',\n",
       " 'repr',\n",
       " 'reversed',\n",
       " 'round',\n",
       " 'runfile',\n",
       " 'set',\n",
       " 'setattr',\n",
       " 'slice',\n",
       " 'sorted',\n",
       " 'staticmethod',\n",
       " 'str',\n",
       " 'sum',\n",
       " 'super',\n",
       " 'tuple',\n",
       " 'type',\n",
       " 'vars',\n",
       " 'zip']"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import builtins\n",
    "dir(builtins)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "664ff782",
   "metadata": {},
   "source": [
    "Python 中只有模块（module），类（class）以及函数（def、lambda）才会引入新的作用域，其它的代码块（如 if/elif/else/、try/except、for/while等）是不会引入新的作用域的，也就是说这些语句内定义的变量，外部也可以访问，如下代码：\n",
    ">>> if True:\n",
    "...  msg = 'I am from Qzxdp'\n",
    "... \n",
    ">>> msg\n",
    "'I am from Qzxdp'\n",
    ">>>\n",
    "\n",
    ">>> def test():\n",
    "...     msg_inner = 'I am from Qzxdp'\n",
    "... \n",
    ">>> msg_inner\n",
    "Traceback (most recent call last):\n",
    "  File \"<stdin>\", line 1, in <module>\n",
    "NameError: name 'msg_inner' is not defined\n",
    ">>>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "02227fb3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "123\n",
      "123\n"
     ]
    }
   ],
   "source": [
    "# 全局变量和局部变量\n",
    "#!/usr/bin/python3\n",
    " \n",
    "num = 1\n",
    "def fun1():\n",
    "    global num  # 需要使用 global 关键字声明\n",
    "    print(num) \n",
    "    num = 123\n",
    "    print(num)\n",
    "fun1() \n",
    "print(num) # 123"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "0c5de34b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100\n",
      "100\n"
     ]
    }
   ],
   "source": [
    "#!/usr/bin/python3\n",
    " \n",
    "def outer():\n",
    "    num = 10\n",
    "    def inner():\n",
    "        nonlocal num   # nonlocal关键字声明\n",
    "        num = 100\n",
    "        print(num)\n",
    "    inner()\n",
    "    print(num)\n",
    "outer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "bbb0d4d1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "11\n"
     ]
    }
   ],
   "source": [
    "# 例子一\n",
    "#!/usr/bin/python3\n",
    " \n",
    "a = 10\n",
    "def test():\n",
    "    global a\n",
    "    a = a + 1\n",
    "    print(a)\n",
    "test()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "832b3828",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "11\n"
     ]
    }
   ],
   "source": [
    "# 例子二\n",
    "#!/usr/bin/python3\n",
    " \n",
    "a = 10\n",
    "def test(a):\n",
    "    a = a + 1\n",
    "    print(a)\n",
    "test(a)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
